package com.ds.yuntukubackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.ds.yuntukubackend.common.ResultUtils;
import com.ds.yuntukubackend.config.CosClientConfig;
import com.ds.yuntukubackend.exception.BusinessException;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.exception.ThrowUtils;
import com.ds.yuntukubackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.utils.DateUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * 文件服务
 * @deprecated 已废弃，改为使用 upload 包的模板方法优化
 */
@Slf4j
@Service
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     * @param multipartFile 文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix){
        //校验图片
        validPicture(multipartFile);
        //图片名称: 时间戳 + 随机数 + 文件后缀
//        String date = DateUtils.formatDate(new Date());  ??????为什么不能用，会报错
        String uuid = RandomUtil.randomString(8);
        String originalFilename = multipartFile.getOriginalFilename();
        String fileSuffix = FileUtil.getSuffix(originalFilename);
        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,fileSuffix);
        //图片上传地址, uploadPathPrefix可以指定为不同的用户id,实现不同用户的图片上传到不同的文件夹
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        //上传图片
        File file = null;
        try {
            //创建临时文件
            file = File.createTempFile(uploadPath, null);
            multipartFile.transferTo(file);
            //上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double picScale = NumberUtil.round(width * 1.0 / height ,2).doubleValue();
            //封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            //uploadPath为相对路径，加上host域名为绝对路径
            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(picScale);
            uploadPictureResult.setPicFormat(imageInfo.getFormat());

            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到对象存储失败 :",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片上传失败");
        }finally {
            this.deleteTempFile(file);
        }
    }

    /**
     * 校验文件是否合法
     * @param multipartfile
     */
    private void validPicture(MultipartFile multipartfile) {
        ThrowUtils.throwIf(multipartfile==null, ErrorCode.PARAMS_ERROR,"文件不能为空");
        //1.校验文件大小
        long fileSize = multipartfile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 10 * ONE_M, ErrorCode.PARAMS_ERROR,"文件大小不能超过10M" );
        //2.校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartfile.getOriginalFilename());
        //允许上传的文件后缀
        final List<String> ALLOWED_SUFFIX = Arrays.asList("png", "jpg", "jpeg", "gif");
        ThrowUtils.throwIf(!ALLOWED_SUFFIX.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"文件格式不合法" );
    }

    /**
     * 删除临时文件
     * @param file
     */
    private void deleteTempFile(File file) {
        if(file == null){
            return;
        }
        //删除临时文件
        boolean deleteResult = file.delete();
        if(!deleteResult){
            log.error("临时文件删除失败，文件地址：{}",file.getAbsolutePath());
        }
    }



//    /**
//     * 通过url上传图片
//     * @param fileUrl 文件路径
//     * @param uploadPathPrefix 上传路径前缀
//     * @return
//     */
//    public UploadPictureResult uploadPictureByUrl(String fileUrl, String uploadPathPrefix){
//        //todo:校验图片
//        validPicture(fileUrl);
//        //图片名称: 时间戳 + 随机数 + 文件后缀
//        String uuid = RandomUtil.randomString(8);
//
//        String originalFilename = FileUtil.mainName(fileUrl);
//        String fileSuffix = FileUtil.getSuffix(originalFilename);
//        String uploadFilename = String.format("%s_%s.%s", DateUtil.formatDate(new Date()),uuid,fileSuffix);
//        //图片上传地址, uploadPathPrefix可以指定为不同的用户id,实现不同用户的图片上传到不同的文件夹
//        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
//        //上传图片
//        File file = null;
//        try {
//            //创建临时文件
//            file = File.createTempFile(uploadPath, null);
//            //todo:下载图片到临时文件
//            HttpUtil.downloadFile(fileUrl,file);
//            //上传图片
//            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
//            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
//            int width = imageInfo.getWidth();
//            int height = imageInfo.getHeight();
//            double picScale = NumberUtil.round(width * 1.0 / height ,2).doubleValue();
//            //封装返回结果
//            UploadPictureResult uploadPictureResult = new UploadPictureResult();
//            //uploadPath为相对路径，加上host域名为绝对路径
//            uploadPictureResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
//            uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
//            uploadPictureResult.setPicSize(FileUtil.size(file));
//            uploadPictureResult.setPicWidth(width);
//            uploadPictureResult.setPicHeight(height);
//            uploadPictureResult.setPicScale(picScale);
//            uploadPictureResult.setPicFormat(imageInfo.getFormat());
//
//            return uploadPictureResult;
//        } catch (Exception e) {
//            log.error("图片上传到对象存储失败 :",e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片上传失败");
//        }finally {
//            this.deleteTempFile(file);
//        }
//    }
//
//    /**
//     * 通过url校验图片
//     * @param fileUrl
//     */
//    private void validPicture(String fileUrl) {
//        //校验非空
//        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR,"文件地址为空");
//        //校验url格式
//        try {
//            new URL(fileUrl);
//        } catch (MalformedURLException e) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址格式不合法");
//        }
//        //校验url协议
//        ThrowUtils.throwIf(!fileUrl.startsWith("http://") && !fileUrl.startsWith("https://"),
//                ErrorCode.OPERATION_ERROR,"仅支持 http 和 https协议的文件地址");
//        //发送HEAD请求验证文件是否存在
//        HttpResponse httpResponse = null;
//        try {
//            httpResponse = HttpUtil.createRequest(Method.HEAD, fileUrl).execute();
//            //为正常返回，无需执行其它操作，可能是该网站不支持head请求，而不是文件不存在
//            if(httpResponse.getStatus() != HttpStatus.HTTP_OK){
//                return;
//            }
//            //校验文件类型
//            String contentType = httpResponse.header("Content-Type");
//            //不为空，校验是否合法，这样校验规则相对宽松
//            if (StrUtil.isNotBlank(contentType)) {
//                // 允许的图片类型
//                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
//                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
//                        ErrorCode.PARAMS_ERROR, "文件类型错误");
//            }
//            //校验文件大小
//            String contentLengthStr = httpResponse.header("Content-Length");
//            if (StrUtil.isNotBlank(contentLengthStr)) {
//                try {
//                    long contentLength = Long.parseLong(contentLengthStr);
//                    final long ONE_M = 1024 * 1024;
//                    ThrowUtils.throwIf(contentLength > 10 * ONE_M, ErrorCode.PARAMS_ERROR,"文件大小不能超过10M" );
//                } catch (NumberFormatException e) {
//                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
//                }
//            }
//        }finally {
//            //释放资源
//            if(httpResponse != null){
//                httpResponse.close();
//            }
//        }
//
//
//
//    }



}
